package com.zhenzu.jucUtil;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 六辆汽车停到三个停车位
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);

        // 模拟六辆汽车
        for (int i = 1; i < 6; i++) {
            new Thread(() -> {
                try {
                    // 抢占停车位
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + " 抢到了车位");

                    // 设置随机的停车时间
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));

                    System.out.println(Thread.currentThread().getName() + " 离开了车位");

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放车位
                    semaphore.release();
                }
            }, String.valueOf(i)).start();
        }
    }
}
